import axios from 'axios'
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/userInfo';

const router = useRouter()


import { showToast } from 'vant';

// import {getToken, removeToken} from './auth'
import errorCode from './errorCode.ts'

// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.withCredentials = true


let apiUrl: string | undefined = ''


// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    //   baseURL:'/api',
    // 超时
    timeout: 20000
})
// console.log('import.meta.env.VITE_BASE_URL',import.meta.env.VITE_BASE_URL)



// request拦截器
service.interceptors.request.use(config => {
    apiUrl = config.url
    if (apiUrl !== '/login.loginbusiness.do') {
     const userStore = useAuthStore();
     const { token } = storeToRefs(userStore)
     if (token) {
      config.headers['X-Token-Id'] = `${token.value}`;
     } 
    }

    // 是否需要设置 token
    //   const isToken = (config.headers || {}).isToken === false
    // if (getToken() && !isToken) {
    //   config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    //   // config.headers['Authorization'] = 'Base ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    //   // config.headers['secret'] = 'abcdefghijklmnopqrstuvwxyz' 
    // }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?';
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName];
            var part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof (value) !== "undefined") {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        url += subPart + encodeURIComponent(value[key]) + "&";
                    }
                } else {
                    url += part + encodeURIComponent(value) + "&";
                }
            }
        }
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    return config
}, error => {
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {

    const code = res.data?.code;
    // 获取错误信息
    // let msg = errorCode['default']
    let msg = ''

    if (code === 0) {
        return res.data
    } else {
        // console.log("****",code)
        // return 
        switch (apiUrl) {
            case '/login.loginbusiness.do':
                msg = res.data.message
                break;
            case '/login.changepwd.do':
                msg = res.data.message
                break;
            // case '/loginuser.fsyzm.do':
            //     // msg = res.data.data[0].name
            //     msg = res.data.message
            //     break;
            default:
                msg = res.data?.message === 'error' ? errorCode['default'] : res.data ?? `[${res.data?.data[0]['error_des']}]${res.data?.data[0]['error_note']}`
                break;
        }

        showToast(msg);
        if (code === 100401) {
   
            setTimeout(() => {
                let protocol = window.location.protocol; // 获取协议部分(http:或https:)
                let hostname = window.location.hostname; // 获取主机名部分
                let port = window.location.port
                let pathname = ""

                if (process.env.NODE_ENV === 'development') {
                    console.log('当前是开发模式');
                    pathname = "/#/"
                } else {
                    console.log('当前是生产模式');
                    pathname = "/vue-common/dist/#/";
                }
                let loginUrl = `${protocol}//${hostname}:${port}${pathname}`
                window.location.href = loginUrl
            }, 2000)

        }
        return res.data
    }

},
    error => {

        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        }
        else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        }
        else if (message.includes("Request failed with status code")) {
            if (message.substr(message.length - 3) == "413") {
                message = "图片太大,请上传8M以下的图片"

            } else {
                message = "系统接口" + message.substr(message.length - 3) + "异常";
            }
        }
        showToast(message);
        return Promise.reject(error)
    }
)

export default service
